package main

import (
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis"

	"time"
)

var RedisClient *redis.Client

func newRedisClient() {
	//创建redis客户端
	RedisClient = redis.NewClient(&redis.Options{
		Addr:     "123.57.250.120:6379",
		Password: "123456",
		DB:       0,
	})
	//测试下客户端
	result, e := RedisClient.Ping().Result()
	fmt.Printf("Ping result =%v \n", result)
	if e == nil && result == "PONG" {
		fmt.Println("new client success ")
	} else {
		panic(fmt.Sprintf("redis 客户端初始化失败 err=%v", e))
	}
}

//init 方法通常用于初始化全局变量的信息
func init() {
	//初始化redis 客户端
	newRedisClient()
}
func main() {
	s, e := RedisClient.Get("name").Result()
	if e == nil {
		fmt.Printf("name= %s \n", s)
	} else {
		fmt.Printf("get name e=%v \n", e)
	}
	p := Person{
		Age:      26,
		Name:     "芮旭乐",
		Sex:      0,
		Brithday: time.Now(),
	}
	err := RedisClient.Set("rxl", p.ToJsonMarshaler(), 0).Err()
	if err == nil {
		fmt.Println("insert sucess")
	} else {
		fmt.Printf("inser err=%v", err)
	}
	result, e := RedisClient.Get("rxl").Result()
	if e != nil {
		fmt.Printf("%v \n", e)
	} else {
		fmt.Printf("rxl =%v", result)
	}
}

type Person struct {
	Age      int
	Name     string
	Sex      int
	Brithday time.Time
}

//但存入的对象复杂的结构体的时候，需要实现序列化
func (p *Person) ToJsonMarshaler() []byte {
	bytes, e := json.Marshal(p)
	if e != nil {
		return nil
	} else {
		return bytes
	}
}
